//
//  LHCountdownTool.m
//  WXYView
//
//  Created by lehuo on 2017/1/6.
//  Copyright © 2017年 lehuo. All rights reserved.
//

#import "LHCountdownTool.h"
static NSTimeInterval smsTime = 60;
static NSTimeInterval stretchTime = 0;
@interface LHCountdownTool ()
@property(nonatomic,assign)NSTimeInterval countdown;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)CountdownType countdownType;
@property(nonatomic,strong)RemainTime remainTime;
@end
@implementation LHCountdownTool

+ (void)getRemainTimeWith:(CountdownType)type time:(NSTimeInterval)time RemainTime:(RemainTime)remainTime
{
    LHCountdownTool *tool = [[LHCountdownTool alloc] init];
    tool.countdownType = type;
    tool.countdown = time;
    tool.remainTime = remainTime;
    stretchTime = time;
    [tool getParams:tool];
}





- (void)getParams:(LHCountdownTool *)tool
{
    self.countdown = tool.countdownType;
    if (tool.countdownType == SMSType)
        self.countdown = smsTime;
    else
    {
        NSDate *date = [NSDate date];
        NSTimeInterval currnentTime = [date timeIntervalSince1970];
        self.countdown = stretchTime - currnentTime;
    }
    self.countdownType = tool.countdownType;
    [self addTimer];
}
#pragma mark - 定时器事件
//添加定时器
- (void)addTimer
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(remainingTimeMethodAction) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        [_timer fire];
    }
}
//移除定时器
- (void)removeTimer
{
    if (self.timer)
    {
        [self.timer invalidate];
        self.timer = nil;
    }

}

- (void)remainingTimeMethodAction
{
    NSString *countdownStr;
    BOOL isFinsih = NO;
    if (self.countdownType == SMSType)
    {
        self.countdown --;
        countdownStr = [NSString stringWithFormat:@"%.0f秒后获取",self.countdown];
        if (self.countdown == 0) {
            [self removeTimer];
            countdownStr = @"重新获取";
            isFinsih = YES;
        }
    }else
    {
        NSInteger ms = self.countdown;
        NSInteger ss = 1;
        NSInteger mi = ss * 60;
        NSInteger hh = mi * 60;
        NSInteger dd = hh * 24;
        
        // 剩余的
        NSInteger day = ms / dd;// 天
        NSInteger hour = (ms - day * dd) / hh;// 时
        NSInteger minute = (ms - day * dd - hour * hh) / mi;// 分
        NSInteger second = (ms - day * dd - hour * hh - minute * mi) / ss;// 秒
        countdownStr = [NSString stringWithFormat:@"距离活动开始还有%zd天%zd时%zd分%zd秒",day,hour,minute,second];
        NSLog(@"%@",countdownStr);
        self.countdown --;
        if (ms == 0) {
            [self removeTimer];
            countdownStr = @"活动开始!";
            isFinsih = YES;
        }
        
       
    }
  
    self.remainTime(countdownStr,isFinsih);
}
@end
